package cn.gson.crm.controller.system;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.DeptDao;
import cn.gson.crm.model.dao.EmpDao;
import cn.gson.crm.model.dao.ImagesDao;
import cn.gson.crm.model.dao.UserDao;
import cn.gson.crm.model.entity.Dept;
import cn.gson.crm.model.entity.Emp;
import cn.gson.crm.model.entity.Images;
import cn.gson.crm.model.entity.Role;
import cn.gson.crm.model.entity.User;
import cn.gson.crm.model.mapper.DeptMapper;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping("/emp")
@Log4j
public class EmpController {
	@Autowired
	private DeptMapper empMapper;
	
	@Autowired
	private EmpDao empDao;
	
	@Autowired
	private DeptDao deptDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private ImagesDao imgDao ;
	/**
	 * 查询所有员工
	 * @param emp
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String,Object> index(Emp emp, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Emp> pageData = empMapper.listEmp(emp);

		PageInfo<Emp> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	@RequestMapping("listusers")
	@ResponseBody
	public Map<String,Object> listusers(User user, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<User> pageData = empMapper.listUsers(user);

		PageInfo<User> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> delete(@PathVariable("id") Long id) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Emp e;
		if (id != null && (e = empDao.findOne(id)) != null) {
			log.info(e.getRemark());
			if(e.getRemark().equals("部门经理")) {
				Dept d=deptDao.findByDeptManager(e.getName());
				d.setDeptManager("");
				e.setDelete(false);
			}else {
				e.setDelete(false);
			}
			obj.put("success", true);
		} else {
			obj.put("message", "此员工不存在！");
		}
		return obj;
	}
	
	@GetMapping({ "add_emp", "add_emp/{id}" })
	public String form(Role role,Dept dept,@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			Emp e = empDao.findOne(id);
			if (e != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("emp", e);
			}
		}
		List<Role> r = empMapper.listRole(role);
		List<Dept> d = empMapper.list(dept);
		model.addAttribute("role", r);
		model.addAttribute("dept", d);
		return "emp/add_emp";
	}

	@PostMapping("save")
	@ResponseBody
	@Transactional
	public Map<String,Object> save(@Valid Emp emp,@Valid User user, BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			if (user.getId()==null&&emp.getId() == null) {
				int count=empMapper.countAccount(emp.getName()+"%");
				if (count>=1) {
					user.setAccount(emp.getName()+count);
					user.setPassword("123456");
					user.setEmp(emp);
					user.setDelete(true);
					user.setEnable(true);
					userDao.save(user);
				}else {
					user.setPassword("123456");
					user.setAccount(emp.getName());
					user.setEmp(emp);
					user.setDelete(true);
					user.setEnable(true);
					userDao.save(user);
				}
				
			} else {
				//编辑的时的两种情况
				if (emp.getName() != null && emp.getTel()!=null &&emp.getBirthday()!=null&&emp.getJob()!=null&&emp.getDept().getName()!=null&&emp.getEntryTime()!=null) {
					//有数据的时候，则表示更新数据
					emp.setName(emp.getName());
					emp.setTel(emp.getTel());
					emp.setBirthday(emp.getBirthday());
					emp.setEntryTime(emp.getEntryTime());
					emp.setSex(emp.getSex());
					emp.setJob(emp.getJob());
					emp.setDept(emp.getDept());
					emp.setRemark(emp.getRemark());
					emp.setDelete(true);
				} else {
					//没有数据，则查出原数据进行覆盖
					Emp e = empDao.findOne(emp.getId());
					emp.setName(e.getName());
					emp.setTel(e.getTel());
					emp.setBirthday(e.getBirthday());
					emp.setEntryTime(e.getEntryTime());
					emp.setSex(e.getSex());
					emp.setJob(e.getJob());
					emp.setDept(null);
					emp.setRemark(e.getRemark());
					emp.setDelete(e.getDelete());
				}
			}
			emp.setDelete(true);
			empDao.save(emp);
			obj.put("success", true);
		}
		return obj;
	}
	
	/**
	 * 查询用户信息
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("edituser")
	public String edituser(
			Long id,
			Model model) {
		if (id != null) {
			/*//根据Id查询就业学员的反馈信息
			User user = userDao.findOne(id);
			//查询所有就业学员的姓名和id
			if (user != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("user", user);
			}*/
		}
		return "emp/edituser";
	}
	/**
	 * 查询用户信息
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("changepassword/{userid}")
	public String changepassword(
			@PathVariable(name = "userid", required = false) Long id,
			Model model) {
		if (id != null) {
			//根据Id查询就业学员的反馈信息
			User user = userDao.findOne(id);
			//查询所有就业学员的姓名和id
			if (user != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("user", user);
			}
		}
		return "emp/change_password";
	}
	
	
	@Value("${upload.dir}")
	private String uploadDir;
	/**
	 * 保存用户信息
	 */
	@PostMapping("saveuser")
	@ResponseBody
	@Transactional
	public Map<String,Object> detailSave(
			@Valid User user,
			BindingResult br,
			@RequestParam(defaultValue="public") String type,
			@RequestParam("file") MultipartFile file,
			HttpServletRequest request) throws IllegalStateException, IOException {
	
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Images img = new Images();
		//设置路径
		if(!file.isEmpty()) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String dateDir = sdf.format(new Date());
		//获取文件后缀名
		String ext = FilenameUtils.getExtension(file.getOriginalFilename());
		String newFileName = UUID.randomUUID().toString()+"."+ext;
		String filePath = String .format("%s/%s/%s",System.getProperty("user.dir") + uploadDir,type,dateDir);
		File fileDir = new File(filePath);
		if(!fileDir.exists()){
			// 如果目录不存在，则创建出来
			fileDir.mkdirs();
		}
		img.setDelete(true);
		img.setImageType(file.getContentType());
		img.setModeType(type);
		img.setName(file.getOriginalFilename());
		img.setPath(String.format("%s/%s/%s", type,dateDir,newFileName));
		img.setSize(file.getSize());
		img.setSuffix(ext);
		img.setUploaddate(new Date());
		//将图片路径保存到数据库
		imgDao.save(img);
		file.transferTo(new File(fileDir, newFileName));
		}
		User u = userDao.findOne(user.getId());
		if(!file.isEmpty()) {
		u.setImages(img);
		}
		u.setName(user.getName());
		userDao.save(u);
		obj.put("success", true);
		
		return obj;
	}
	
	/**
	 * 修改密码（后台）
	 * @param user
	 * @param br
	 * @return
	 */
	@PostMapping("changeuserpass")
	@Transactional
	public Map<String,Object> changeuserpass(@Valid User user, BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		User u = userDao.findOne(user.getId());
		u.setPassword(user.getPassword());
		userDao.save(u);
		obj.put("success", true);
		return obj;
	}
	
}
